<template>
  <div>
    <!-- <van-empty description="当前无任务" /> -->
    <!-- <van-button @click="setSearchWorkType = true" style="text-align: center;">筛选</van-button> -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" style="min-height: 800px;">
        <van-cell v-for="(item, index) in taskListDataIndex" :key="item.taskId"
          @click="HandleClick(item.taskId, item.type, item.role)" :class="{ dark: index % 2 !== 0 }">
          <!-- <div @touchstart="getTouchStart(item.taskId)" @touchend="getTouchEnd()"> -->
          <div>
            <van-row type="flex" justify="space-between" class="schedule-time">
              <van-col span="9">
                <span class="icon iconfont icon-shijian"></span>
                {{ item.date }}
              </van-col>
              <van-col span="2">
                <span class="icon iconfont icon-wujiaoxing-" v-if="isCurTask(item.taskId)"
                  :style="{ color: 'orange', fontSize: '24px' }"></span>
              </van-col>
              <van-col span="13" :style="{ textAlign: 'right' }">{{ item.time }}</van-col>
            </van-row>
            <van-row type="flex" justify="space-between">
              <van-col span="6" style="color:#888">
                <span class="icon iconfont icon-id"></span>
                <span>{{ item.taskId }}</span>
              </van-col>
              <van-col span="5">
                <!-- <span class="icon iconfont icon-type"></span> -->
                <van-tag color="#ffe1e1" text-color="#ad0000">
                  <span v-if="item.type === 0">普通</span>
                  <span v-else-if="item.type === 1">工务</span>
                  <span v-else-if="item.type === 2">电务</span>
                  <span v-else-if="item.type === 3">巡道</span>
                  <span v-else-if="item.type === 4">列检</span>
                  <span v-else-if="item.type === 5">其它</span>
                  <span v-else-if="item.type === 6">机务</span>
                  <span v-else-if="item.type === 7">调车</span>
                  <span v-else-if="item.type === 8">商检</span>
                  <span v-else>未知</span>
                </van-tag>
              </van-col>
              <van-col span="7">
                <!-- <span class="icon iconfont icon-jiaoseguanli"></span> -->
                <van-tag type="primary" plain>
                  <span v-if="item.role === 0">创建人</span>
                  <span v-else-if="item.role === 1">{{ taskSetting.showInformation.managerShowName }}</span>
                  <span v-else-if="item.role === 2">联络员</span>
                  <span v-else-if="item.role === 3">防护员</span>
                  <span v-else-if="item.role === 4">作业人员</span>
                  <span v-else-if="item.role === 5 && item.type === 4">巡道工</span>
                  <span v-else-if="item.role === 5 && item.type === 5">作业人员</span>
                  <span v-else-if="item.role === 6 && item.type === 4">列检员</span>
                  <span v-else-if="item.role === 6 && item.type === 8">商检员</span>
                  <span v-else-if="item.role === 7">作业组长</span>
                  <span v-else>未知</span>
                </van-tag>
              </van-col>
              <van-col span="6" :style="{ textAlign: 'right' }">
                <!-- <span class="icon iconfont icon-Status"></span> -->
                <van-tag v-if="item.state === 1">待审核</van-tag>
                <van-tag type="warning" v-else-if="item.state === 2">审核中</van-tag>
                <van-tag type="primary" v-else-if="item.state === 3">已批准</van-tag>
                <van-tag type="danger" v-else-if="item.state === 4">已拒绝</van-tag>
                <van-tag type="success" v-else-if="item.state === 5">进行中</van-tag>
                <van-tag type="warning" v-else-if="item.state === 6 && taskSetting.haveEvacuateState">撤离中</van-tag>
                <van-tag v-else-if="item.state === 6 && !taskSetting.haveEvacuateState">已完成</van-tag>
                <van-tag v-else-if="item.state === 7">已销毁</van-tag>
                <van-tag v-else-if="item.state === 8">已终止</van-tag>
                <van-tag v-else>未知</van-tag>
              </van-col>
            </van-row>
          </div>
        </van-cell>
      </van-list>
    </van-pull-refresh>
    <van-popup v-model="setSearchWorkType" round position="bottom">
      <van-checkbox-group v-model="SearchWorkType" direction="horizontal"
        style="margin-top: 60px; margin-bottom: 30px; icon-size=24px; font-size: 18px; display: flex; justify-content: center; align-items: center;  ">
        <van-checkbox v-for="(item, index) in workTypeList" :key="index" :name="item.name" :label="item.value">{{
          item.label }}</van-checkbox>
      </van-checkbox-group>
      <van-checkbox-group v-model="SearchWorkState" direction="horizontal"
        style="margin-top: 60px; margin-bottom: 30px; icon-size=24px; font-size: 18px; display: flex; justify-content: center; align-items: center;  ">
        <van-checkbox v-for="(item, index) in workStateList" :key="index" :name="item.name" :label="item.value">{{
          item.label }}</van-checkbox>
      </van-checkbox-group>
      <div class="submit-area" style="text-align: center;">
        <van-button round @click="setSearchWorkType = false">完成</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { getFormatDate, getFormatHourMinute, getFormatDateTime } from '../utils/datetime'
import { requestMyTaskBriefList, getTaskTypeStr, getTaskStateStr, requestMyWorkTypeTaskList, getMyPermission, getUserInfo, getTaskSetting } from '../utils/taskUtils'
import { mapGetters, mapMutations } from 'vuex'
import { getStationNames } from '@/api/line_data'
import { eventBus } from '../bus'

export default {
  name: '',
  components: {},
  props: {},
  data() {
    return {
      tasklist: [],
      workTypeList: [],
      workStateList: [],
      setSearchWorkType: false,
      SearchWorkType: [],
      SearchWorkState: [],
      refreshing: true,
      allTaskInfos: [],
      taskListData: [],
      curTaskId: 0,
      loading: false,
      finished: false,
      touchLoop: 0
    }
  },
  computed: {
    taskListDataIndex() {
      if (this.SearchWorkType && this.SearchWorkType.length) {
        return this.taskListData.filter((item, index) => {
          if (this.SearchWorkState.includes(item.state)) return item
        })
      } else {
        return this.taskListData.filter((item, index) => {
          return item
        })
      }
    },
    ...mapGetters(['userId', 'deviceId', 'permission', 'workType', 'station', 'taskSetting'])
  },
  watch: {},
  created() { },
  mounted() {
    this.sockets.subscribe('TaskChangeBriefInfo', async (channelMsg) => {
      if (channelMsg.props.type === 'create') {
        let isMyTask = false
        if (channelMsg.data.userIds instanceof Array && channelMsg.data.userIds.indexOf(this.userId) >= 0) isMyTask = true
        if (channelMsg.data.deviceIds instanceof Array && channelMsg.data.deviceIds.indexOf(this.deviceId) >= 0) isMyTask = true
        if (this.workType.includes(channelMsg.data.type) && this.station.includes(channelMsg.data.station)) isMyTask = true // 2023-07-12 WP 按照任务工种类型获取
        if (isMyTask) {
          this.refreshAllTask()
          if (!this.taskSetting.haveCTCTask) {
            const notice = `新增${getTaskTypeStr(channelMsg.data.type)}(id: ${channelMsg.data.taskId})，状态:${getTaskStateStr(channelMsg.data.state)}！`
            this.$dialog
              .confirm({
                message: notice,
                confirmButtonText: '签收'
              })
              .then(() => {
                var task = { manager: [{ id: this.userId, type: 'user' }] }
                this.$http.put(`/task/receive?taskId=${channelMsg.data.taskId}`).then((res) => {
                  if (res.data.code === 0 && res.data.data.isSuccess) {
                    this.$http.put(`/task/update?taskId=${channelMsg.data.taskId}`, task)
                  } else {
                    const notice = '该任务已有人签收'
                    this.$dialog.alert({
                      message: notice
                    })
                  }
                })
              })
          }
        }
      } else {
        const idx = this.taskListData.findIndex((item) => item.taskId === parseInt(channelMsg.data.taskId))
        if (idx >= 0) {
          // 与当前任务列表中的任务有关
          if (channelMsg.props.type === 'update') {
            this.taskListData[idx].state = channelMsg.data.state
            const notice = `${getTaskTypeStr(channelMsg.data.type)}(id: ${channelMsg.data.taskId})变更，状态:${getTaskStateStr(channelMsg.data.state)}！`
            this.$dialog.alert({
              message: notice
            })
          } else if (channelMsg.props.type === 'delete') {
            this.refreshAllTask()
            const notice = `${getTaskTypeStr(channelMsg.data.type)}(id: ${channelMsg.data.taskId}) 删除！`
            this.$dialog.alert({
              message: notice
            })
          }
          // this.$notify(notice)
          // Vue.set(this.allTaskInfos[idx], 'state', channelMsg.data.state)
        }
      }
    })
    eventBus.$on('IdChange', (id) => {
      this.refreshing = true
      this.initData()
    })
  },
  beforeDestroy() {
    eventBus.$off('IdChange')
    this.sockets.unsubscribe('TaskChangeBriefInfo')
  },
  methods: {
    ...mapMutations(['setUserId', 'setDeviceId', 'setPermission', 'setOrgIds', 'setMyStationIds', 'setStationIds', 'setWorkType', 'setStation', 'setTaskSetting']),
    async initData() {
      if (this.taskSetting.defaultPremissions) {
        this.setPermission(this.taskSetting.defaultPremissions)
      } else {
        getMyPermission(parseInt(this.userId), 0).then((response) => {
          if (response.code === 0) {
            this.setPermission(response.data.op_perm.task)
          }
        })
      }
      this.SearchWorkType = []
      const response = await getUserInfo(parseInt(this.userId))
      const response2 = await getTaskSetting()
      if (response2.code === 0) this.setTaskSetting(response2.data.taskSetting)
      if (response.code === 0) {
        this.setStation(response.data.stationIds)
        this.setOrgIds(response.data.org)
        if (this.taskSetting.defaultStationIds) {
          this.setStation(this.taskSetting.defaultStationIds)
        }
        if (this.taskSetting.defaultOrg) {
          this.setOrgIds(this.taskSetting.defaultOrg)
        }
        if (response.data.job) {
          switch (response.data.job) {
            case '电务': this.setWorkType([2])
              break
            case '工务': this.setWorkType([1])
              break
            case '列检': this.setWorkType([4])
              break
            case '商检': this.setWorkType([8])
              break
            case '调车': this.setWorkType([7])
              break
            case '机务': this.setWorkType([6])
              break
            default: this.setWorkType([0])
          }
        } else this.setWorkType([0])
        if (response.data.taskTypeIds && response.data.taskTypeIds.length) {
          this.setWorkType(response.data.taskTypeIds)
        }
        const workTypeList = { 1: '工务', 2: '电务', 3: '巡道', 4: '列检', 6: '机务', 7: '调车', 8: '商检' }
        if (this.taskSetting.haveEvacuateState) {
          this.workStateList = [
            { name: 3, value: 3, label: '已批准' },
            { name: 5, value: 5, label: '进行中' },
            { name: 6, value: 6, label: '撤离中' },
            { name: 8, value: 8, label: '已终止' }
          ]
        } else {
          this.workStateList = [
            { name: 3, value: 3, label: '已批准' },
            { name: 5, value: 5, label: '进行中' },
            { name: 6, value: 6, label: '已完成' },
            { name: 8, value: 8, label: '已终止' }
          ]
        }
        for (const i in this.workType) if (this.workType[i]) this.workTypeList.push({ name: this.workType[i], value: this.workType[i], label: workTypeList[this.workType[i]] })
        this.SearchWorkType = this.workType
        this.SearchWorkState = [3, 5, 6, 8]
        const response3 = await getStationNames()
        if (response3.code === 0) {
          var stationNameData = response3.data
          var stationNameList = []
          var stationNameList2 = []
          for (var key in stationNameData) {
            stationNameList2.push({
              text: stationNameData[key].stationName,
              value: stationNameData[key].stationNum
            })
            if (this.station.includes(stationNameData[key].stationNum)) {
              stationNameList.push({
                text: stationNameData[key].stationName,
                value: stationNameData[key].stationNum
              })
            }
          }
          this.setStationIds(stationNameList2)
          this.setMyStationIds(stationNameList)
        }
      }
      this.refreshing = true
      this.refreshAllTask()
    },
    clickit() { },
    onRefresh() {
      this.refreshAllTask()
    },
    waitIdentity() {
      return new Promise((resolve, reject) => {
        if (!this.userId && !this.deviceId) {
          this.$toast('等待identity..')
          setTimeout(() => {
            resolve('ok')
          }, 1000)
        } else {
          resolve('ok')
        }
      })
    },
    refreshAllTask() {
      this.taskListDataIndex = []
      this.getAllTaskInfos()
        .then(() => {
          this.getListData()
          this.refreshing = false
          // this.$toast('获取任务列表成功')
        })
        .catch((err) => {
          this.refreshing = false
          this.$dialog.alert({ message: '获取任务列表失败' })
          this.$dialog.alert({ message: err })
        })
    },
    async getAllTaskInfos(deviceId = 0, userId = 0) {
      this.tasklist = []
      const showStates = [3, 5, 6, 8]
      if (!userId && !deviceId) {
        await this.waitIdentity()
        if (!this.userId && !this.deviceId) {
          this.$toast('身份信息为空')
          Promise.reject(new Error('no identity'))
        }
        deviceId = this.deviceId
        userId = this.userId
      }
      const response = await requestMyTaskBriefList(deviceId, userId)
      var response2
      if (this.taskSetting.receiveMyWorkTypeTask) {
        const currentTime = new Date() // 获取最近24小时内的任务
        currentTime.setDate(currentTime.getDate() + 1)
        const dataTimeA = getFormatDateTime(currentTime)
        currentTime.setDate(currentTime.getDate() - 2)
        const dataTimeB = getFormatDateTime(currentTime)
        const timeRange = []
        timeRange.push(dataTimeB)
        timeRange.push(dataTimeA)
        const timeType = 'createTime'
        if (this.workType && this.workType.length) {
          response2 = await requestMyWorkTypeTaskList(this.workType, timeRange, timeType, this.station)
        }
      }
      if (response.code === 0) {
        const currentTimestamp = new Date().getTime()
        this.allTaskInfos = {}
        this.tasklist = []
        response.data.item.forEach((item) => {
          if (showStates.includes(item.state) && currentTimestamp < item.createTime + 24 * 60 * 60 * 1000) {
            if (item.relInfo.userRole) {
              item.myRole = item.relInfo.userRole
            } else if (item.relInfo.deviceRole) {
              item.myRole = item.relInfo.deviceRole
            } else if (item.relInfo.creater) {
              item.myRole = 0
            } else item.myRole = -1
            this.tasklist.push(item.taskId)
            this.allTaskInfos[item.taskId] = item
          }
        })
        if (this.taskSetting.receiveMyWorkTypeTask && this.workType && this.workType.length) {
          response2.data.item.forEach((item) => {
            if (showStates.includes(item.state) && !this.tasklist.includes(item.taskId)) {
              item.myRole = -1
              this.tasklist.push(item.taskId)
              this.allTaskInfos[item.taskId] = item
            }
          })
        }
        // this.allTaskInfos = data.data
      }
    },
    async getListData() {
      // this.allTaskInfos
      //   .sort((a, b) => {
      //     // switch (a.state) {
      //     //   case 5:
      //     //     if (b.state === 5) {
      //     //       return a.beginTime_plan - b.beginTime_plan
      //     //     } else {
      //     //       return -1
      //     //     }
      //     //   case 6:
      //     //   case 7:
      //     //     if (b.state === 6 || b.state === 7) {
      //     //       return a.beginTime_plan - b.beginTime_plan
      //     //     } else {
      //     //       return 1
      //     //     }
      //     //   default:
      //     //     if (b.state === 3) {
      //     //       return 1
      //     //     } else if (b.state === 6 || b.state === 7) {
      //     //       return -1
      //     //     } else {
      //     //       return a.beginTime_plan - b.beginTime_plan
      //     //     }
      //     // }
      //     return a.beginTime_plan - b.beginTime_plan
      //   })
      //   .sort((a, b) => {
      //     if (a.state === 5) {
      //       if (b.state === 5) {
      //         return 0
      //       } else {
      //         return -1
      //       }
      //     }
      //   })

      this.tasklist.sort((a, b) => b - a)
      this.taskListData = []
      let item
      for (const key in this.tasklist) {
        item = this.allTaskInfos[this.tasklist[key]]
        const task = { taskId: item.taskId, type: item.type, state: item.state, role: item.myRole }
        const beginDate = new Date(item.beginTime_plan)
        const endDate = new Date(item.endTime_plan)

        const beginDateStr = getFormatDate(beginDate)
        const endDateStr = getFormatDate(endDate)
        const diffDate = parseInt((new Date(endDateStr) - new Date(beginDateStr)) / 1000 / 60 / 60 / 24)

        task.date = getFormatDate(beginDate)
        task.time = getFormatHourMinute(beginDate) + '~' + (diffDate ? `(+${diffDate}d)` : '') + getFormatHourMinute(endDate)
        this.taskListData.push(task)
      }
      if (this.taskSetting.haveCTCTask && this.taskListData[0]) {
        let trainPlanInfo = { trainNumber: '无' }
        if (this.taskListData[0].type === 4 || this.taskListData[0].type === 6 || this.taskListData[0].type === 7 || this.taskListData[0].type === 8) {
          const taskId = this.taskListData[0].taskId
          var data2 = await this.$http.get('/task/planWorkTaskInfo', { params: { taskId } })
          data2 = data2.data
          if (data2.code === 0) {
            trainPlanInfo = data2.data
          }
        }
        const notice = `最新${getTaskTypeStr(this.taskListData[0].type)}(id: ${this.taskListData[0].taskId})，车次号:${trainPlanInfo.trainNumber}，状态:${getTaskStateStr(this.taskListData[0].state)}！`
        if (this.taskListData[0].state !== 6) {
          this.$dialog
            .confirm({
              message: notice,
              confirmButtonText: '打开' // 修改签收功能为打开任务
            })
            .then(() => {
              this.HandleClick(this.taskListData[0].taskId, this.taskListData[0].type, -1)
              // var task = { manager : [{id: this.userId, type: "user"}] }
              // this.$http.put(`/task/receive?taskId=${taskListData[0].taskId}`).then(
              //   (res)=>{
              //     console.log(res)
              //     if(res.data.code==0 && res.data.data.isSuccess) {
              //       this.$http.put(`/task/update?taskId=${taskListData[0].taskId}`, task)
              //     }
              //     else {
              //       const notice = `该任务已有人签收`
              //       this.$dialog.alert({
              //         message: notice
              //       })
              //     }
              //   }
              // )
            })
        }
      }
    },
    isCurTask(id) {
      return this.curTaskId === id
    },
    // getTouchStart(id) {
    //   clearTimeout(this.loop) // 再次清空定时器，防止重复注册定时器
    //   this.loop = setTimeout(this.HandleLongTouch, 800, id)
    // },
    // getTouchEnd() {
    //   clearTimeout(this.loop) // 清空定时器，防止重复注册定时器
    // },
    HandleClick(taskId, type, role) {
      const path = this.getTaskInfoPath(type)
      this.$router.push({ path, query: { taskId, role } })
    },
    getTaskInfoPath(type) {
      switch (type) {
        case 0:
          return '/taskInfo_Normal'
        case 1:
          return '/taskInfo_GW'
        case 2:
          return '/taskInfo_DW'
        case 3:
          return '/taskInfo_XD'
        case 4:
          return '/taskInfo_LJ'
        case 5:
          //  2023-07-13 WP
          return '/taskInfo_QT'
        case 6:
          return '/taskInfo_JW'
        case 7:
          return '/taskInfo_DC'
        case 8:
          return '/taskInfo_SJ'
        default:
          return ''
      }
    },
    // HandleLongTouch(id) {
    //   // this.tmpId = id
    //   this.$dialog.confirm({
    //     title: '任务设定',
    //     message: '确定变更当前任务？',
    //     beforeClose: (action, done) => {
    //       if (action === 'confirm') {
    //         setTimeout(() => {
    //           this.curTaskId = id
    //           done()
    //         }, 1000)
    //       } else {
    //         done()
    //       }
    //     }
    //   })
    //   // .then(() => {
    //   //   console.log(`确认将${id}变更为当前任务`)
    //   //   this.curTaskId = id
    //   // })
    //   // .catch(() => {
    //   //   console.log('取消变更')
    //   // })
    // },
    beforeClose(action, done) {
      if (action === 'confirm') {
        setTimeout(
          (id) => {
            this.curTaskId = id
            done()
          },
          1000,
          this.tmpId
        )
      } else {
        done()
      }
    },
    onLoad() {
      // // 异步更新数据
      // // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      // setTimeout(() => {
      //   for (let i = 0; i < 10; i++) {
      //     this.list.push(this.list.length + 1)
      //   }

      //   // 加载状态结束
      //   this.loading = false

      //   // 数据全部加载完成
      //   if (this.list.length >= 40) {
      //     this.finished = true
      //   }
      // }, 1000)
      this.finished = true
    }
  }
}
</script>

<style lang="less" scoped>
.van-cell {

  // background-color: #fff;
  // font-size: 36px;
  .icon {
    font-size: 36px;
    margin-right: 10px;
  }

  // line-height: 70px;
  .schedule-time {
    color: #888;
  }
}

.dark {
  background-color: #f7f8fa;
}
</style>
